<template>
    <div class="ctLayout">
        <div class="countPie">
            <div class="rate">
                <count
                    :total="total.complainTotal"
                    icon="EditPen"
                    iconBack="#F56C6C"
                    color="#F56C6C"
                >
                    <template #title>
                        <span>被投诉次数</span>
                    </template>
                </count>
               
                <count
                    :total="total.view"
                    icon="View"
                    iconBack="#8fbd56"
                    color="#8fbd56"
                >
                    <template #title>
                        <span>今日点击次数</span>
                    </template>
                </count>
            </div>
            <div class="rate">
                <rate
                    :total="indentNum.total"
                    :todayNum="indentNum.end_t"
                    :yesdayNum="indentNum.start_t"
                    icon="Handbag"
                    iconBack="#e984b1"
                >
                <template #title>
                        <span>订单总数</span>
                    </template>
                </rate>
                
                <rate
                    :total="IncomeNum.total"
                    :todayNum="IncomeNum.end_t"
                    :yesdayNum="IncomeNum.start_t"
                    icon="Money"
                    iconBack="#e7c354"
                    prefix="$"
                >
                <template #title>
                        <span>营销总量</span>
                    </template>
                </rate>
            </div>
            
            <div class="echars">
                <div class="tag">
                    <span>选择统计时间</span>
                    <el-config-provider :locale="zhCn">
                        <el-date-picker
                            v-model="countTime"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            size="large"
                        />
                    </el-config-provider>
                    <p>
                        <el-button type="primary" @click="queryEchars">立即查询</el-button>
                        <el-button type="success" @click="clearQuery">查询全部</el-button>
                    </p>
                </div>

                <div class="echarsItem">
                    <pie-echarts :option="indentInfoPie" ref="echarsPie">
                        <template #title><span>客房营销额占比</span></template>
                    </pie-echarts>

                    <pie-echarts :option="indentRoomBar" ref="echarsBar">
                        <template #title><span>客房销售量</span></template>
                    </pie-echarts>
                </div>
              
            </div>
        </div>
    </div> 
</template>

<script lang="ts" setup>
import { ref, onBeforeMount, reactive } from 'vue'
import { pieEcharts,rate, count } from '@/components'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { get } from '@/http/axios' 
import { getCookies } from '@/utils/cookies'
import { getToday, getYesday } from '@/utils/format'
import { ElMessage } from 'element-plus'

type roomIndentType = {
    room: {
        room_name: string
    }
    roomNum: number
}
type indentInfoType = {
    room_name: string
    total_price: number
}

const indentRoomBar = ref({
    xAxis: {
        data: [] as Array<string>,
    },
    yAxis: {
        type: 'value',
        name: '售出数量',
        axisTick:{
            length: 1
        }
    },
    series: [
        {
            type: 'bar',
            data: [] as Array<number>

        }
    ],
    
})
const indentInfoPie = ref({
    legend: {
        orient: 'vertical',
        x: 'right',
        data: [] as Array<string>
    },
    series: [
        {
            type: 'pie',
            radius: ['100%', '65%'], //1. 饼相较于盒子的大小 2. 内圆的大小
            avoidLabelOverlap: false,
            label: {
                show: false,      //是否饼中对应的名称 false时 只展示移入的元素
                position: 'center'    //显示的位置 showtrue时center会重叠 效果不好
            },
            emphasis: {
                label: {
                show: true,
                fontSize: '25',
                fontWeight: 'bold'
                }
            },
            data: [] as Array<{ value: number, name: string }>
        }
    ]
})

const echarsPie = ref()
const echarsBar = ref()
let id = ref<number | string>()
//第一排统计的数据
let total = reactive({
    complainTotal: 0,
    view: 0
})
//时间选择器数据
let countTime = ref()
//第二排订单
let indentNum = reactive({
    total: 0,
    start_t: 0,
    end_t: 0
})
//第二排营销量
let IncomeNum = reactive({
    total: 0,
    start_t: 0,
    end_t: 0
})
onBeforeMount(() => {
    id.value = getCookies('id')
    //统计 点击量和投诉量
    getComplain()
    getClickNum()

    IndentInfo()
    betweenTimeIndentNum()
    betweenTimeIncomeNum()

    //客房销售量 柱状图
    getIndentRoom()
})
//查看酒店范围时间内的订单数量 -- 订单数
function getIndentTotal(start_time: number = 0, end_time: number = 0) {
    return new Promise((reslve,rej) => {
        get('/order/queryHotelOrderNum',{
            hotel_id: id.value,
            start_time,
            end_time
        }).then(res => {
            return reslve(res.result)
        }).catch(err => {
            ElMessage.error('统计收入出错')
            console.log(err);
        })
    })
}
//查看酒店范围时间内的收入 -- 营销额
function getIncomeTotal(start_time: number = 0, end_time: number = 0) {
    return new Promise((reslove) => {
        get('/order/queryHotelOrderMoney',{
            hotel_id: id.value,
            start_time,
            end_time
        }).then(res => {
            if (!res.result) {
                return reslove(0)
            }
            return reslove(res.result)
        }).catch(err => {
            ElMessage('时间内酒店收入加载失败')
            console.log(err);
        })
    })

}
//范围时间内的房间产生的订单量 --- 客房销售额
function getIndentRoom() {
    indentRoomBar.value.xAxis.data = []
    get('/order/queryRoomOrder',{
        hotel_id: id.value,
        start_time: countTime.value?new Date(countTime.value[0]).getTime():0,
        end_time: countTime.value?new Date(countTime.value[1]).getTime():0
    }).then(res => {
        console.log('房间信息',res.result);
        
        return handelRoomIndent(res.result)
    }).catch(err => {
        ElMessage.error('房间订单量加载失败')
        console.log(err);
    })
}
//查询4和9状态的订单信息
function IndentData(order_code:number) {
    return new Promise((reslove,rej) => { 
        get('/order/queryHotel',{
            hotel_id: id.value,
            order_state: order_code,
            user_code: 0,
            start_time: countTime.value?new Date(countTime.value[0]).getTime():0,
            end_time: countTime.value?new Date(countTime.value[1]).getTime():0,
            pageNum: 1,
            pageSize: 1000,
        }).then(res => {
            reslove(res.result.content)
        }).catch(err => {
            ElMessage.error('订单信息加载失败')
            console.log(err);
        })
    })
}
//酒店投诉量
function getComplain() {
    get('/complain/complainHotel', { hotel_id: id.value }).then(res => {
        total.complainTotal = res.result
    }).catch(err => {
        ElMessage.error('投诉量加载失败')
        console.log(err)
    })
}
//今日点击量
function getClickNum() {
    get('/count/getClick',{ hotel_id: id.value }).then(res => {
        total.view = res.result.today_click
    }).catch(err => {
        ElMessage.error('今日点击率加载失败')
        console.log(err)
    })
}
// 查询时间段内的
function queryEchars(){
    getIndentRoom()
    IndentInfo()
}
function clearQuery() {
    countTime.value = null
    getIndentRoom()
    IndentInfo()
}
// 查询时间段内订单状态为4和9 的订单信息 然后转换程echars表格饼图
function IndentInfo() {
    indentInfoPie.value.legend.data = []
    Promise.all([IndentData(4),IndentData(9)]).then((res:Array<any>) => {
        console.log('订单信息',res);
        let arr = [] as Array<indentInfoType>
        res.forEach(el => arr.push(...el) )
        return handelIndentInfo(arr)
    })
}
// 查询昨天和今天的订单量
function betweenTimeIndentNum() {
    const to = getToday()
    const yes = getYesday()
    Promise.all([getIndentTotal(), getIndentTotal(to.today,to.nowTime), getIndentTotal(yes.yesday,yes.today)])
    .then(res => {
        indentNum.total = res[0]
        indentNum.end_t = res[1]
        indentNum.start_t = res[2]
    })
}
// 查询昨天和今天的销售额
function betweenTimeIncomeNum() {
    const to = getToday()
    const yes = getYesday()
    Promise.all([getIncomeTotal(), getIncomeTotal(to.today,to.nowTime), getIncomeTotal(yes.yesday,yes.today)])
    .then(res => {
        console.log(res);
        IncomeNum.total = res[0]
        IncomeNum.end_t = res[1]
        IncomeNum.start_t = res[2]
    })
}
//处理酒店房间参数订单量为柱状图
function handelRoomIndent(arr:Array<roomIndentType>){
    let xAxisData = [] as Array<string>
    let seriesData = [] as Array<number>
    arr.forEach(el => {
        let xx = xAxisData.findIndex(ele => ele === el.room.room_name)        
        if (xx != -1) {
            seriesData[xx] = seriesData[xx] + el.roomNum
        } else if (el.roomNum !== 0) {
            xAxisData.push(el.room.room_name)
            seriesData.push(el.roomNum)  
        }
    })
    indentRoomBar.value.xAxis.data = xAxisData
    indentRoomBar.value.series[0].data = seriesData
    echarsBar.value.initEcharts()
}
//处理酒店完成的订单为饼状图
function handelIndentInfo(arr: Array<indentInfoType>) {
    let legend = [] as Array<string>
    let seriesData = [] as Array<{ value: number, name: string }>
    arr.forEach(el => {
        let xx = legend.findIndex(ele => ele === el.room_name)
        if (xx !== -1) {
            seriesData[xx].value = seriesData[xx].value + el.total_price
        } else {
            legend.push(el.room_name)
            seriesData.push({ value: el.total_price, name: el.room_name })
        }
    })
    indentInfoPie.value.legend.data = legend
    indentInfoPie.value.series[0].data = seriesData
    echarsPie.value.initEcharts()
}


</script>

<style lang="scss" scoped>
.ctLayout{
    width: 100%;
    @include flexColumnCenter;
    gap: 2px 0;
    @include allBack;
}

.countPie{
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    flex-wrap: wrap;
    gap: 20px;
    & div{
        max-width: 100%;
    }
}
.tag{
    background: rgb(245, 108, 108,0.3);
    padding: 10px 20px;
    align-self: flex-end;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 20px;
    border-radius: 8px;
    & span:nth-child(1){
        background: #ffffff;
        padding: 5px 15px;
        font-size: 14px;
        box-sizing: border-box;
        border-radius: 6px;
        color: #61666d;
        white-space: nowrap;
    }
}
.rate{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 20px;
    & div{
        width: calc((100% - 40px) / 3);
    }

}
.dataKinds{
    width: 210px !important;
    height: 35px;
    border: 1px solid var(--el-border-color);
    border-radius: 30px;
    font-size: 13px;
    box-sizing: border-box;
    background: #f1f2f3;
    @include flexRowCenter;
    & span{
        padding: 0 20px;
        height: 100%;
        border-radius: 30px;
        @include flexRowCenter;
    }
}
.echars{
    width: 100%;
    border-radius: 8px;
    background: white;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    padding: 20px;
    gap: 20px;
    box-sizing: border-box;
    box-shadow: var(--el-box-shadow);
    & div{
        max-width: 100%;
    }

}
.echarsItem{
    border-top: 1px solid var(--el-border-color);
    padding-top: 20px;
    width: 100%;
    display: flex;
    align-items: flex-end;
    flex-wrap: wrap;
    gap: 20px;

    & div{
        width: calc((100% - 40px) / 3);
    }
    & div:nth-child(1){
        height: 300px;
    }
    & div:nth-child(2){
        flex-grow: 2;
        height: 400px;
    }
}
.num{
    margin-left: 10px;
    font-size: 16px;
    color: #213547;
    font-weight: 600;
}
</style>